package com.weiyin.examination.course;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.chad.library.adapter.base.BaseViewHolder;
import com.weiyin.examination.R;
import com.weiyin.examination.adapter.CourseA7Adapter;
import com.weiyin.examination.application.Constant;
import com.weiyin.examination.dialog.CourseA7Dialog;
import com.weiyin.examination.listener.CourseInterface;
import com.weiyin.examination.listener.DialogListResultInterface;
import com.weiyin.examination.listener.DialogShowListener;
import com.weiyin.examination.module.AnswerModule;
import com.weiyin.examination.module.TestModule;
import com.weiyin.examination.util.LayoutHelper;
import com.weiyin.examination.util.LogUtil;
import com.weiyin.examination.util.SPUtil;
import com.weiyin.examination.view.GridLayoutManager;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author njf
 *         Created by lenovo on 2017/9/19.
 */

public class CourseA7 extends Course implements CourseA7Adapter.OnItemClickInterface {
    private View rootView;
    private Activity activity;
    private ClickAble clickAble;

    private RecyclerView recyclerView;
    private CourseA7Adapter courseA7Adapter;
    private TextView titleLayoutNextTextView, titleLayoutLastTextView, titleLayoutSubjectContentTextView,
            titleLayoutSubjectScoreTextView, titleLayoutNumberTextView, titleTicketNumber;
    private RelativeLayout titleLayoutNumberRl;

    private TestModule testModule;
    private List<TestModule> testModuleList;
    private List<AnswerModule> answerModuleList;
    private int courseIndex;
    private Handler mHandler = new Handler();
    private Map<String, String> map;

    private double score;

    @Override
    public void onCreate(Activity activity, ViewFlipper contain, List<TestModule> courseEntities, int index) {
        if (rootView == null) {
            rootView = LayoutInflater.from(activity).inflate(R.layout.coursea7_layout, null);
            LayoutHelper layoutHelper = new LayoutHelper(activity);
            layoutHelper.scaleView(rootView);

            contain.addView(rootView);
            this.testModuleList = courseEntities;
            this.activity = activity;
            this.courseIndex = index;
            this.testModule = testModuleList.get(index);
            clickAble = new ClickAble();
            map = new HashMap<>();
            if (testModule != null) {
                if (testModule.getRightAnswerList() != null) {
                    this.answerModuleList = testModule.getRightAnswerList();
                }
            }
            initView();
        }
    }

    @Override
    public void initView() {
        titleLayoutNextTextView = (TextView) rootView.findViewById(R.id.titleLayoutNextTextView);
        titleLayoutLastTextView = (TextView) rootView.findViewById(R.id.titleLayoutLastTextView);
        titleLayoutSubjectContentTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectContentTextView);
        titleLayoutSubjectScoreTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectScoreTextView);
        titleLayoutNumberTextView = (TextView) rootView.findViewById(R.id.titleLayoutNumberTextView);
        titleLayoutNumberRl = (RelativeLayout) rootView.findViewById(R.id.titleLayoutNumberRl);
        titleTicketNumber = (TextView) rootView.findViewById(R.id.titleTicketNumber);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.courseA7RecyclerView);
        courseA7Adapter = new CourseA7Adapter(activity, R.layout.coursea7_tiem_layout, testModule.getSelectionList());
        recyclerView.setLayoutManager(new GridLayoutManager(activity, 3, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(courseA7Adapter);
        courseA7Adapter.setOnItemClickInterface(this);

        titleLayoutNextTextView.setOnClickListener(clickAble);
        titleLayoutLastTextView.setOnClickListener(clickAble);
        titleLayoutNumberRl.setOnClickListener(clickAble);
    }

    private void initViewData() {
        if (testModule != null) {
            titleTicketNumber.setText("准考证号：" + "" + testModule.getTickNumber());

            titleLayoutLastTextView.setVisibility(courseIndex == 0 ? View.GONE : View.VISIBLE);
            titleLayoutNextTextView.setVisibility(courseIndex == testModuleList.size() - 1 ? View.GONE : View.VISIBLE);

            titleLayoutSubjectContentTextView.setText((courseIndex + 1) + "丶" + testModule.getSubjectTitle());
            titleLayoutSubjectScoreTextView.setText("（" + testModule.getScore() + "分）");
            titleLayoutNumberTextView.setText("第" + (courseIndex + 1) + "题/第" + (testModuleList.size()) + "题");
        }
    }


    @Override
    public void onItemClick(final BaseViewHolder helper, final int position) {
        List<String> data = new ArrayList<>();
        final String s = testModule.getSelectionList().get(position).getSelectContent();
        getList(s, data);
        CourseA7Dialog courseA7Dialog = new CourseA7Dialog(activity, R.style.BlueToothDialogStyle, data, testModule.getSelectionList().get(position).getSubjectContent());
        courseA7Dialog.show();
        courseA7Dialog.setDialogListResultInterface(new DialogListResultInterface() {
            @Override
            public void result(List<String> data) {
                if (data != null && data.size() > 0) {
                    helper.setGone(R.id.courseA7ItemTextAnswer, true);

                    StringBuilder stringBuffer = new StringBuilder();
                    for (int i = 0; i < data.size(); i++) {
                        stringBuffer.append(data.get(i));
                        if (i < data.size() - 1) {
                            stringBuffer.append(",");
                        }
                    }
                    helper.setText(R.id.courseA7ItemTextAnswer, stringBuffer.toString());
                    map.put(position + "", stringBuffer.toString());
                } else {
                    helper.setGone(R.id.courseA7ItemTextAnswer, false);
                    map.put(position + "", "");
                }
            }
        });
    }

    private void getList(String str, List<String> data) {
        if (str.contains(Constant.SUBJECT_URL_CONTAINS)) {
            String s = str.substring(0, str.indexOf(Constant.SUBJECT_URL_CONTAINS));
            data.add(s);
            Log.i(TAG, s + "|" + str.substring(str.indexOf(Constant.SUBJECT_URL_CONTAINS) + 1));
            getList(str.substring(str.indexOf(Constant.SUBJECT_URL_CONTAINS) + 1), data);
        } else {
            data.add(str);
        }
    }

    class ClickAble implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.titleLayoutNextTextView:

                    dialogShowListener.dialogShow(1, courseIndex, resultMap());
                    courseInterface.courseInterfaceResult(Constant.NEXT_KNOWLEDGE, courseIndex + 1);
                    break;
                case R.id.titleLayoutLastTextView:
                    dialogShowListener.dialogShow(1, courseIndex, resultMap());
                    courseInterface.courseInterfaceResult(Constant.LAST_KNOWLEDGE, courseIndex - 1);
                    break;
                case R.id.titleLayoutNumberRl:
                    dialogShowListener.dialogShow(1, courseIndex, resultMap());
                    dialogShowListener.dialogShow(0, courseIndex, resultMap());
                    break;
                default:
                    break;
            }
        }
    }

    private boolean resultMap() {

        Constant.getScreen(activity, SPUtil.getSharedPreferencesData(activity, "number") + "_" + (courseIndex + 1),SPUtil.getSharedPreferencesData(activity, "number")+"_"+ (courseIndex + 1));
        if (map != null) {
            score = 0;
            boolean result = false;
            int index = 0;
            for (int i = 0; i < answerModuleList.size(); i++) {
                if (!StringUtils.isEmpty(map.get(i + ""))) {
                    String mapResult = map.get(i + "");
                    if (mapResult.contains(",") && answerModuleList.get(i).getAnswerContentList().get(0).contains(",")) {
                        List<String> mapResultList = new ArrayList<>();
                        List<String> answerList = new ArrayList<>();
                        getList(mapResult, mapResultList);
                        getList(answerModuleList.get(i).getAnswerContentList().get(0), answerList);
                        boolean mapRes = true;
                        if (mapResultList.size() == answerList.size()) {
                            for (String s : mapResultList) {
                                if (!answerList.contains(s)) {
                                    mapRes = false;
                                    break;
                                }
                            }
                            if (mapRes)
                                score += Double.valueOf(answerModuleList.get(i).getScore());
                        }
                    } else {
                        if (mapResult.equals(answerModuleList.get(i).getAnswerContentList().get(0))) {
                            score += Double.valueOf(answerModuleList.get(i).getScore());
                        }
                    }
                    index++;
                }
            }
            LogUtil.i(TAG,"score="+score);
            SPUtil.setSharedPreferencesData(activity.getApplicationContext(), CourseA7.class.getSimpleName(), score + "");
            if (index == answerModuleList.size()) {
                result = true;
            }
            return result;
        } else {

            LogUtil.i(TAG,"score="+score);
            SPUtil.setSharedPreferencesData(activity.getApplicationContext(), CourseA7.class.getSimpleName(),   "0");
            return false;
        }
    }

    @Override
    public void setCourseInterface(CourseInterface courseInterface) {
        this.courseInterface = courseInterface;
    }

    @Override
    public void setCourseDialogListener(DialogShowListener dialogListener) {
        this.dialogShowListener = dialogListener;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void show(List<TestModule> courseEntities, int index, String type) {
        initViewData();
    }

    @Override
    public void stop() {

    }

    @Override
    public void destroy() {

    }
}
